package io.wanghaoran.project.module.system.controller;

import io.wanghaoran.project.framework.security.util.SecurityUtils;
import io.wanghaoran.project.module.system.entity.UserTokensLog;
import io.wanghaoran.project.module.system.service.UserTokensLogService;
import io.wanghaoran.project.common.base.domain.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;

/**
 * <p>
 * Token使用量统计控制器
 * </p>
 *
 * @author system
 * @since 2025-07-30
 */
@Api(tags = "Token使用量统计")
@RestController
@RequestMapping("/system/tokenStatistics")
@RequiredArgsConstructor
public class TokenStatisticsController {

    private final UserTokensLogService userTokensLogService;

    @ApiOperation("获取一周内Token使用量统计")
    @GetMapping("/weeklyUsage")
    public Result<Map<String, Object>> getWeeklyTokenUsage() {
        String currentUser = SecurityUtils.getUserName();
        boolean isAdmin = "admin".equals(currentUser);
        
        // 获取最近7天的日期（从今天往前推6天到今天，共7天）
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -6);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        
        // 获取7天的日期列表（按升序排列）
        List<Date> dateList = new ArrayList<>();
        calendar.setTime(startDate);
        for (int i = 0; i < 7; i++) {
            dateList.add(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        // 查询数据
        List<UserTokensLog> logs = userTokensLogService.list()
            .stream()
            .filter(log -> log.getCreateTime() != null)
            .filter(log -> {
                Date createTime = log.getCreateTime();
                return !createTime.before(startDate) && !createTime.after(endDate);
            })
            .filter(log -> isAdmin || currentUser.equals(log.getUserName()))
            .collect(Collectors.toList());
        
        // 按日期分组统计
        Map<String, Long> dailyUsage = new LinkedHashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        
        for (Date date : dateList) {
            String dateStr = dateFormat.format(date);
            
            long totalTokens = logs.stream()
                .filter(log -> {
                    Calendar logCal = Calendar.getInstance();
                    logCal.setTime(log.getCreateTime());
                    
                    Calendar dateCal = Calendar.getInstance();
                    dateCal.setTime(date);
                    
                    return logCal.get(Calendar.YEAR) == dateCal.get(Calendar.YEAR) &&
                           logCal.get(Calendar.MONTH) == dateCal.get(Calendar.MONTH) &&
                           logCal.get(Calendar.DAY_OF_MONTH) == dateCal.get(Calendar.DAY_OF_MONTH);
                })
                .mapToLong(log -> log.getDeductTokens() != null ? log.getDeductTokens() : 0L)
                .sum();
                
            dailyUsage.put(dateStr, totalTokens);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("days", new ArrayList<>(dailyUsage.keySet()));
        result.put("values", new ArrayList<>(dailyUsage.values()));
        result.put("isAdmin", isAdmin);
        
        return Result.success(result);
    }

    @ApiOperation("获取一周内调用次数统计")
    @GetMapping("/weeklyCalls")
    public Result<Map<String, Object>> getWeeklyCallCount() {
        String currentUser = SecurityUtils.getUserName();
        boolean isAdmin = "admin".equals(currentUser);
        
        // 获取最近7天的日期（从今天往前推6天到今天，共7天）
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -6);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        
        // 获取7天的日期列表（按升序排列）
        List<Date> dateList = new ArrayList<>();
        calendar.setTime(startDate);
        for (int i = 0; i < 7; i++) {
            dateList.add(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        // 查询数据
        List<UserTokensLog> logs = userTokensLogService.list()
            .stream()
            .filter(log -> log.getCreateTime() != null)
            .filter(log -> {
                Date createTime = log.getCreateTime();
                return !createTime.before(startDate) && !createTime.after(endDate);
            })
            .filter(log -> isAdmin || currentUser.equals(log.getUserName()))
            .collect(Collectors.toList());
        
        // 按日期分组统计调用次数
        Map<String, Long> dailyCalls = new LinkedHashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        
        for (Date date : dateList) {
            String dateStr = dateFormat.format(date);
            
            long callCount = logs.stream()
                .filter(log -> {
                    Calendar logCal = Calendar.getInstance();
                    logCal.setTime(log.getCreateTime());
                    
                    Calendar dateCal = Calendar.getInstance();
                    dateCal.setTime(date);
                    
                    return logCal.get(Calendar.YEAR) == dateCal.get(Calendar.YEAR) &&
                           logCal.get(Calendar.MONTH) == dateCal.get(Calendar.MONTH) &&
                           logCal.get(Calendar.DAY_OF_MONTH) == dateCal.get(Calendar.DAY_OF_MONTH);
                })
                .count();
                
            dailyCalls.put(dateStr, callCount);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("days", new ArrayList<>(dailyCalls.keySet()));
        result.put("values", new ArrayList<>(dailyCalls.values()));
        result.put("isAdmin", isAdmin);
        
        return Result.success(result);
    }

}